package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: itheima
 * @create: 2022-04-04 10:55
 */
@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private IApUserSearchService apUserSearchService;

    /**
     * 根据用户录入关键字全文检索文章列表，根据文章发布时间降序排序
     *
     * @param dto 入参条件
     * @return 分页文章列表
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) throws IOException {
        //1.构建搜索请求对象SearchRequest，指定查询索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //2.创建SearchSourceBuilder，指定查询各种参数请求体 包含:查询方式，分页，排序，聚合，高亮
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.1 设置查询方式：全文检索查询  查询文章标题字段
        sourceBuilder.query(QueryBuilders.matchQuery("title", dto.getSearchWords()).operator(Operator.AND));
        //2.2 设置分页
        Long from = (dto.getPage() - 1) * dto.getSize();
        sourceBuilder.from(from.intValue());
        sourceBuilder.size(dto.getSize());

        //2.3 设置排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //2.4 TODO 设置高亮
        //sourceBuilder.highlighter()

        //3.将SearchSourceBuilder关联到SearchRequest
        searchRequest.source(sourceBuilder);

        //4.执行全文检索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //5.封装分页结果
        //5.1 获取总记录数
        long total = searchResponse.getHits().getTotalHits().value;

        //5.2 获取当前页数据
        List<ApArticleSearch> list = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                ApArticleSearch apArticleSearch = JSON.parseObject(sourceAsString, ApArticleSearch.class);
                list.add(apArticleSearch);
            }
        }

        //6.异步记录用户搜索历史
        User user = UserThreadLocalUtil.get();
        apUserSearchService.saveSearchRecord(dto.getSearchWords(), user.getUserId(), dto.getEquipmentId());
        return new PageResponseResult(dto.getPage(), dto.getSize(), total, list);
    }


}
